package com.itheima.admin.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.admin.service.WemediaNewsAutoScanService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsPageReqDto;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.w3c.dom.stylesheets.LinkStyle;

import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.admin.task
 */
@Component
@Slf4j
public class SyncArticleTask {

    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    @XxlJob("synArticleTask")
    public ReturnT<String> syncArticleJob(String param){
        log.info("开始执行同步文章任务: param={}",param);
        //程调用自媒体查询文章 并处理
        WmNewsPageReqDto dto = new WmNewsPageReqDto();
        dto.setStatus((short)BusinessConstants.WmNewsConstants.STATUS_PASS);
        //这一句为第10天优化
        dto.setEndPubDate(new Date());
        ResultVo<List<WmNewsVo>> listResultVo = wmNewsFeign.list4ArticleSync(dto);
        // 对结果判断
        if (listResultVo.isSuccess()){
            List<WmNewsVo> list = listResultVo.getData();
            log.info("同步文章任务完成: param={},size={}",param,list.size());
            XxlJobLogger.log("同步文章任务完成: size={}",list.size());
            if (CollectionUtils.isNotEmpty(list)){
                // 有需要同步的数据
                for (WmNewsVo wmNewsVo : list) {
                    // 同步文章数据
                    boolean flag = wemediaNewsAutoScanService.syncArticleInfo(wmNewsVo);
                    if (flag){
                        log.info("同步文章数据成功: wmNewsId={}",wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据成功: wmNewsId={}",wmNewsVo.getId());
                    }else{
                        log.info("同步文章数据失败: wmNewsId={}",wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据失败: wmNewsId={}",wmNewsVo.getId());
                    }
                }
            }
            return ReturnT.SUCCESS;
        }else {
            log.info("同步文章任务失败: param={}， 调用自媒体微服查询失败",param);
            return ReturnT.FAIL;
        }
    }
}
